<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ChatGPT</title>
<!--  标签页图标显示-->
    <link rel="shortcut icon" href="/static/favicon-32x32.png" type="image/x-icon">
    <style type="text/css">
        *{
        padding: 0;
        margin: 0;
        }
        html{
            height: 100%;
            width: 100%;
            display: block;
        }
        body{
            height: 100%;
            width: 100%;
            display: flex;
            border: #aaaaaa;
            align-items: center;
            justify-content: center;
        }
        .all-container {
            height: 88vh;
            width: 100vw;
            min-height: 480px;
            display: flex;
            border: #aaaaaa;
            flex-flow: row;
            justify-content: center;
            align-items: center;
        }
        .left-container{
            height: inherit;
            width: 160px;
            min-width: 100px;
            max-width: 200px;
            border-radius: 4px;
            border: 0.5px solid #D0D0D0;
            background-color: #EEEEEE;
            display: flex;
            flex-flow: column;
        }
        .chat-list{
            overflow-y: scroll;
            flex: 1;
        }
        .chat-list .selected{
            background-color: #D0D0D0;
        }
        .chat-list::-webkit-scrollbar{
            display: none;
        }
        .chat, .newchat{
            border-bottom: 0.5px solid #cccccc;
            border-top: 0.5px solid #cccccc;;
            background-color: #EFEFEF;
            padding: 10px;
        }
        .newchat{
            color: #317d8a;
        }
        .newchat:hover{
            background-color: #E8E8E8;
        }
        .chat:hover{
            background-color: #E8E8E8;
        }
        .right-container{
            height: inherit;
            width: 760px;
            min-width: 220px;
            border-radius: 4px;
            border: 0.5px solid #cccccc;
            background-color: #f5f5f5;
            display: flex;
            flex-flow: column;
            overflow: hidden;
        }
        .content{
            position: relative;
            font-size: 15px;
            width: calc(100% - 40px);
            padding: 20px;
            overflow-y: scroll;
            flex: 1;
        }
        /* 设置滚动条的样式 */
        .content::-webkit-scrollbar {
            width:10px;
        }
        /* 滚动槽 */
        .content::-webkit-scrollbar-track {
            border-radius:8px;
        }
        /* 滚动条滑块 */
        .content::-webkit-scrollbar-thumb {
            border-radius:10px;
            background:rgba(0,0,0,0);
        }
        /* 滚动条滑块移入显示 */
        .content:hover::-webkit-scrollbar-thumb{
            background: rgba(0, 0, 0, 0.1);
        }
        .bubble{
            max-width: 400px;
            padding: 10px;
            border-radius: 5px;
            position: relative;
            color: #000;
            word-wrap:break-word;
            word-break:normal;
        }
        .item-left .bubble{
            margin-left: 15px;
            background-color: #fff;
        }
        .item-left .bubble:before{
            content: "";
            position: absolute;
            width: 0;
            height: 0;
            border-left: 10px solid transparent;
            border-top: 10px solid transparent;
            border-right: 10px solid #fff;
            border-bottom: 10px solid transparent;
            left: -20px;
        }
        .item-right .bubble{
            margin-right: 15px;
            background-color: #9eea6a;
        }
        .item-right .bubble:before{
            content: "";
            position: absolute;
            width: 0;
            height: 0;
            border-left: 10px solid #9eea6a;
            border-top: 10px solid transparent;
            border-right: 10px solid transparent;
            border-bottom: 10px solid transparent;
            right: -20px;
        }
        .item{
            margin-top: 15px;
            display: flex;
            width: 100%;
        }
        .item.item-right{
            justify-content: flex-end;
        }
        .item.item-center{
            justify-content: center;
        }
        .item.item-center span{
            font-size: 12px;
            padding: 2px 4px;
            color: #fff;
            background-color: #dadada;
            border-radius: 3px;
            -moz-user-select:none; /*火狐*/
            -webkit-user-select:none; /*webkit浏览器*/
            -ms-user-select:none; /*IE10*/
            -khtml-user-select:none; /*早期浏览器*/
            user-select:none;
        }

        .avatar img{
            width: 42px;
            height: 42px;
            border-radius: 50%;
        }
        .input-area{
            border-top:0.5px solid #e0e0e0;
            height: 150px;
            display: flex;
            flex-flow: column;
            background-color: #fff;
        }
        textarea{
            flex: 1;
            padding: 5px;
            font-size: 14px;
            border: none;
            cursor: pointer;
            overflow-y: auto;
            overflow-x: hidden;
            outline:none;
            resize:none;
        }
        button{
            margin-left: 5px;
            margin-right: 5px;
            padding: 10px;
        }
        .button-area{
            display: flex;
            min-height: 40px;
            margin-right: 10px;
            line-height: 40px;
            padding: 5px;
            justify-content: flex-end;
        }
        .button-area button{
            max-width: 80px;
            border: none;
            outline: none;
            border-radius: 4px;
            float: right;
            cursor: pointer;
        }
        .button-area #chmod-btn, .button-area #del-btn {
            max-width: 120px;
        }
        .button-area button:hover{
            background-color: #e0e0e0;
        }
        .button-area button:active{
            background-color: #bdbdbd;
        }
        /* markdown列表样式 */
        .markdown ol, .markdown ul {
            padding-left: 1.5em;
        }
        .markdown ol {
            list-style-type: decimal;
        }
        .markdown ul {
            list-style-type: disc;
        }

        /* markdown代码样式 包含行号 */
        .markdown pre {
            padding: 0.5em;
            overflow: auto;
            background-color: #2b2b2b;
            border-radius: 4px;
        }
        .markdown pre code {
            background-color: #2b2b2b;
            padding: .1rem .1rem;
            color: #f8f8f2;
        }
        /* 代码复制按钮格式 */
        .markdown pre .code-copy-btn {
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            -khtml-user-select: none;
            user-select: none;
            position: absolute;
            right: 12px;
            font-size: 12px;
            line-height: 1;
            cursor: pointer;
            color: hsla(0,0%,54.9%,.8);
            transition: color .1s;
        }
        /* 行内代码段样式 */
        .markdown code {
            color: #c7254e;
            background-color: #f9f2f4;
            border-radius: 2px;
            padding: .25rem .25rem;
        }
        .markdown p:not(:last-child){
            padding-bottom: 20px;
        }
        .menu{
            position: absolute;
            top: 0;
            right: 0;
            padding: 0;
            display: none;
        }
        .menu button{
            width: 60px;
            height: 25px;
            padding: 2px;
            font-size: 6px;
            border: 1px solid #A0A0A0;
            border-radius: 4px;
            outline: none;
            background-color: #fff;
            cursor: pointer;
            display: none;
        }
        .head-area{
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            background-color: #fafafa;
            border-bottom: 0.5px solid #e0e0e0;
        }
        .head-left{
            display: flex;
            align-items: center;
            justify-content: flex-start;
        }
        .head-info{
            display: flex;
            flex-flow: column;
            justify-content: center;
            align-items: flex-start;
        }
        .head-chat-name{
            font-size: 24px;
            font-family: “Arial”,”Microsoft YaHei”,”黑体”,”宋体”,sans-serif;
            font-weight: bold;
            margin-left: 10px;
        }
        .head-chat-info{
            font-size: 12px;
            color: #9e9e9e;
            margin-left: 10px;
        }
        .head-btns{
            display: flex;
            justify-content: flex-end;
            align-items: center;
        }
        .svg-icon {
            width: 2em;
            height: 2em;
        }

        .svg-icon:hover path,
        .svg-icon:hover polygon,
        .svg-icon:hover rect {
          fill: #6bab6b;
        }

        .svg-icon path,
        .svg-icon polygon,
        .svg-icon rect {
          fill: #3d3c3c;
        }

        .svg-icon circle {
          stroke: #3d3c3c;
          stroke-width: 1;
        }
        .toggle-btn{
            padding-left: 10px;
            padding-right: 10px;
        }

        #toggle-chats-btn {
            display: none;
        }

        @media (max-width: 768px) {
            .left-container {
                display: none;
            }

            #toggle-chats-btn {
                display: block;
            }

            .content{
                font-size: 14px;
            }
        }
        #settings-dialog {
            display: none;
            position: absolute;
            border-radius: 5px;
            background-color: #f1f1f1;
            padding: 20px;
            border: 2px solid #ccc;
            z-index: 2; /* Sit on top */
        }
        .setting-menus{
            width: 100%;
            display: flex;
            justify-content: center;
            flex-direction: column;
            align-items: center;
        }
        .setting-menu{
            min-width: 200px;
            display: flex;
            flex-flow: column;
            justify-content: center;
            align-items: center;
        }
        .setting {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            margin-top: 10px;
            padding: 8px;
        }
        .setting input{
            max-width: 200px;
            height: 35px;
            font-size: 18px;
            text-align: center;
            border-radius: 6px;
            border: 1px solid #A0A0A0;
            outline: none;
        }
        .settings-close-btn{
            width: 100%;
            display: flex;
            justify-content: flex-end;
            align-items: center;
        }
        .setting-label{
            font-size: 18px;
            font-family: “Arial”,”Microsoft YaHei”,”黑体”,”宋体”,sans-serif;
            font-weight: bold;
            padding-right: 10px;
        }
        .setting-sub-label{
            font-size: 12px;
            color: #9e9e9e;
        }
        .label-svg-button{
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .label-svg-button div{
            padding-left: 5px;
            padding-right: 5px;
        }


    </style>
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS_HTML"></script>
    <script src="https://cdn.staticfile.org/clipboard.js/2.0.4/clipboard.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/styles/a11y-dark.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/highlight.min.js"></script>
    <!-- and it's easy to individually load additional languages -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/languages/go.min.js"></script>

</head>
<script>
    // toggle-chats-btn按下 设置left-container可见
    function toggle_settings_dialog() {
        if($("#settings-dialog").css("display") === "none"){
            $("#api-key").val(config.apiKey);
            $("#user-id").val(config.userId);
            $("#password").val(config.password);

            let top = $(".content").offset().top;
            let left = $(".content").offset().left;
            let width = $(".content").width();
            let height = $(".content").height()+$(".input-area").height();
            $("#settings-dialog").css("top", top);
            $("#settings-dialog").css("left", left);
            $("#settings-dialog").css("width", width);
            $("#settings-dialog").css("height", height);
        } else {
            // 获取设置值
            console.log("关闭设置");
            let user_change_flag = false;
            if (config.userId !== $("#user-id").val() || config.password !== $("#password").val()){
                user_change_flag = true;
            }
            config.apiKey = $("#api-key").val();
            config.userId = $("#user-id").val();
            config.password = $("#password").val();
            // 保存设置
            localStorage.setItem("config", JSON.stringify(config));
            if (user_change_flag){
                // 刷新页面
                location.reload();
            }
        }
        $("#settings-dialog").toggle();
    }
    $(document).ready(function () {
        $("#toggle-chats-btn").click(function () {
            $(".left-container").toggle();
        });
        $("#toggle-setting-btn").click(function () {
            toggle_settings_dialog();
        });

    });

</script>
<body>
    <div class="all-container">

        <div id="settings-dialog">
            <div class="settings-close-btn" onclick="toggle_settings_dialog()">
                <svg class="svg-icon" viewBox="0 0 20 20">
                    <path fill="none" d="M15.898,4.045c-0.271-0.272-0.713-0.272-0.986,0l-4.71,4.711L5.493,4.045c-0.272-0.272-0.714-0.272-0.986,0s-0.272,0.714,0,0.986l4.709,4.711l-4.71,4.711c-0.272,0.271-0.272,0.713,0,0.986c0.136,0.136,0.314,0.203,0.492,0.203c0.179,0,0.357-0.067,0.493-0.203l4.711-4.711l4.71,4.711c0.137,0.136,0.314,0.203,0.494,0.203c0.178,0,0.355-0.067,0.492-0.203c0.273-0.273,0.273-0.715,0-0.986l-4.711-4.711l4.711-4.711C16.172,4.759,16.172,4.317,15.898,4.045z"></path>
                </svg>
            </div>
            <div class="setting-menus">
                <div class="setting-menu">
                    <div class="setting-label" style="font-size: 30px">
                        设置
                    </div>
                    <div class="setting">
                        <div class="setting-label">
                            <div>用户ID</div>
                            <div class="setting-sub-label">
                                用于绑定你的云端聊天记录
                            </div>
                        </div>
                        <input type="text" id="user-id" name="user_id">
                    </div>
                    <div class="setting">
                        <div class="setting-label">
                            <div>密码</div>
                            <div class="setting-sub-label">
                                访问密码，后台若需要则需要输入
                            </div>
                        </div>
                        <input type="password" id="password" name="password">
                    </div>
                    <div class="setting">
                        <div class="setting-label">
                            <div>API Key</div>
                            <div class="setting-sub-label">
                                当输入API Key后,可跳过访问密码
                            </div>
                        </div>
                        <input type="text" id="api-key" name="api_key">
                    </div>
                    <div class="setting">
                        <div class="label-svg-button">
                            <div class="setting-label">
                                <div>下载用户记录</div>
                                <div class="setting-sub-label">
                                    下载个人用户记录或所有用户记录
                                </div>
                            </div>
                            <div id="userDictFileDownload">
                                <svg class="svg-icon" viewBox="0 0 20 20">
                                    <path fill="none" d="M15.608,6.262h-2.338v0.935h2.338c0.516,0,0.934,0.418,0.934,0.935v8.879c0,0.517-0.418,0.935-0.934,0.935H4.392c-0.516,0-0.935-0.418-0.935-0.935V8.131c0-0.516,0.419-0.935,0.935-0.935h2.336V6.262H4.392c-1.032,0-1.869,0.837-1.869,1.869v8.879c0,1.031,0.837,1.869,1.869,1.869h11.216c1.031,0,1.869-0.838,1.869-1.869V8.131C17.478,7.099,16.64,6.262,15.608,6.262z M9.513,11.973c0.017,0.082,0.047,0.162,0.109,0.226c0.104,0.106,0.243,0.143,0.378,0.126c0.135,0.017,0.274-0.02,0.377-0.126c0.064-0.065,0.097-0.147,0.115-0.231l1.708-1.751c0.178-0.183,0.178-0.479,0-0.662c-0.178-0.182-0.467-0.182-0.645,0l-1.101,1.129V1.588c0-0.258-0.204-0.467-0.456-0.467c-0.252,0-0.456,0.209-0.456,0.467v9.094L8.443,9.553c-0.178-0.182-0.467-0.182-0.645,0c-0.178,0.184-0.178,0.479,0,0.662L9.513,11.973z"></path>
                                </svg>
                            </div>
                        </div>
                        <div class="label-svg-button">
                            <div class="setting-label">
                                <div>上传并合并用户记录</div>
                                <div class="setting-sub-label">
                                    上传并合并个人用户记录或所有用户记录
                                </div>
                            </div>
                            <div>
                                <label for="userDictFileUpload">
                                    <svg class="svg-icon" viewBox="0 0 20 20">
                                        <path fill="none" d="M8.416,3.943l1.12-1.12v9.031c0,0.257,0.208,0.464,0.464,0.464c0.256,0,0.464-0.207,0.464-0.464V2.823l1.12,1.12c0.182,0.182,0.476,0.182,0.656,0c0.182-0.181,0.182-0.475,0-0.656l-1.744-1.745c-0.018-0.081-0.048-0.16-0.112-0.224C10.279,1.214,10.137,1.177,10,1.194c-0.137-0.017-0.279,0.02-0.384,0.125C9.551,1.384,9.518,1.465,9.499,1.548L7.76,3.288c-0.182,0.181-0.182,0.475,0,0.656C7.941,4.125,8.234,4.125,8.416,3.943z M15.569,6.286h-2.32v0.928h2.32c0.512,0,0.928,0.416,0.928,0.928v8.817c0,0.513-0.416,0.929-0.928,0.929H4.432c-0.513,0-0.928-0.416-0.928-0.929V8.142c0-0.513,0.416-0.928,0.928-0.928h2.32V6.286h-2.32c-1.025,0-1.856,0.831-1.856,1.856v8.817c0,1.025,0.832,1.856,1.856,1.856h11.138c1.024,0,1.855-0.831,1.855-1.856V8.142C17.425,7.117,16.594,6.286,15.569,6.286z"></path>
                                    </svg>
                                </label>
                                <input type="file" id="userDictFileUpload" style="display:none;">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="left-container">
            <div class="chat-list">
                <div class="newchat" id="newchat">添加新的对话</div>

            </div>
        </div>
        <div class="right-container">
            <div class="head-area">
                <div class="head-left">
                    <div class="avatar">
                        <img src="/static/chatgpt.png" alt="">
                    </div>
                    <div class="head-info">
                        <div class="head-chat-name">默认对话</div>
                        <div class="head-chat-info">共0条记录</div>
                    </div>
                </div>
                <div class="head-right">
                    <div class="head-btns">
                        <a href="https://github.com/LiangYang666/ChatGPT-Web">
                            <div class="toggle-btn">
                                <svg class="svg-icon" viewBox="-2 -2 20 20">
                                    <!-- GitHub标志 -->
                                    <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.012 8.012 0 0 0 16 8c0-4.42-3.58-8-8-8z"/>
                                </svg>
                            </div>
                        </a>
                        <div class="toggle-btn" id="toggle-chats-btn">
                            <svg class="svg-icon" viewBox="0 0 20 20">
                                <path d="M10,1.445c-4.726,0-8.555,3.829-8.555,8.555c0,4.725,3.829,8.555,8.555,8.555c4.725,0,8.555-3.83,8.555-8.555C18.555,5.274,14.725,1.445,10,1.445 M10,17.654c-4.221,0-7.654-3.434-7.654-7.654c0-4.221,3.433-7.654,7.654-7.654c4.222,0,7.654,3.433,7.654,7.654C17.654,14.221,14.222,17.654,10,17.654 M14.39,10c0,0.248-0.203,0.45-0.45,0.45H6.06c-0.248,0-0.45-0.203-0.45-0.45s0.203-0.45,0.45-0.45h7.879C14.187,9.55,14.39,9.752,14.39,10 M14.39,12.702c0,0.247-0.203,0.449-0.45,0.449H6.06c-0.248,0-0.45-0.202-0.45-0.449c0-0.248,0.203-0.451,0.45-0.451h7.879C14.187,12.251,14.39,12.454,14.39,12.702 M14.39,7.298c0,0.248-0.203,0.45-0.45,0.45H6.06c-0.248,0-0.45-0.203-0.45-0.45s0.203-0.45,0.45-0.45h7.879C14.187,6.848,14.39,7.051,14.39,7.298"></path>
                            </svg>
                        </div>
                        <div class="toggle-btn" id="toggle-setting-btn">
                            <svg class="svg-icon" viewBox="0 0 20 20">
                                <path d="M17.498,11.697c-0.453-0.453-0.704-1.055-0.704-1.697c0-0.642,0.251-1.244,0.704-1.697c0.069-0.071,0.15-0.141,0.257-0.22c0.127-0.097,0.181-0.262,0.137-0.417c-0.164-0.558-0.388-1.093-0.662-1.597c-0.075-0.141-0.231-0.22-0.391-0.199c-0.13,0.02-0.238,0.027-0.336,0.027c-1.325,0-2.401-1.076-2.401-2.4c0-0.099,0.008-0.207,0.027-0.336c0.021-0.158-0.059-0.316-0.199-0.391c-0.503-0.274-1.039-0.498-1.597-0.662c-0.154-0.044-0.32,0.01-0.416,0.137c-0.079,0.106-0.148,0.188-0.22,0.257C11.244,2.956,10.643,3.207,10,3.207c-0.642,0-1.244-0.25-1.697-0.704c-0.071-0.069-0.141-0.15-0.22-0.257C7.987,2.119,7.821,2.065,7.667,2.109C7.109,2.275,6.571,2.497,6.07,2.771C5.929,2.846,5.85,3.004,5.871,3.162c0.02,0.129,0.027,0.237,0.027,0.336c0,1.325-1.076,2.4-2.401,2.4c-0.098,0-0.206-0.007-0.335-0.027C3.001,5.851,2.845,5.929,2.77,6.07C2.496,6.572,2.274,7.109,2.108,7.667c-0.044,0.154,0.01,0.32,0.137,0.417c0.106,0.079,0.187,0.148,0.256,0.22c0.938,0.936,0.938,2.458,0,3.394c-0.069,0.072-0.15,0.141-0.256,0.221c-0.127,0.096-0.181,0.262-0.137,0.416c0.166,0.557,0.388,1.096,0.662,1.596c0.075,0.143,0.231,0.221,0.392,0.199c0.129-0.02,0.237-0.027,0.335-0.027c1.325,0,2.401,1.076,2.401,2.402c0,0.098-0.007,0.205-0.027,0.334C5.85,16.996,5.929,17.154,6.07,17.23c0.501,0.273,1.04,0.496,1.597,0.66c0.154,0.047,0.32-0.008,0.417-0.137c0.079-0.105,0.148-0.186,0.22-0.256c0.454-0.453,1.055-0.703,1.697-0.703c0.643,0,1.244,0.25,1.697,0.703c0.071,0.07,0.141,0.15,0.22,0.256c0.073,0.098,0.188,0.152,0.307,0.152c0.036,0,0.073-0.004,0.109-0.016c0.558-0.164,1.096-0.387,1.597-0.66c0.141-0.076,0.22-0.234,0.199-0.393c-0.02-0.129-0.027-0.236-0.027-0.334c0-1.326,1.076-2.402,2.401-2.402c0.098,0,0.206,0.008,0.336,0.027c0.159,0.021,0.315-0.057,0.391-0.199c0.274-0.5,0.496-1.039,0.662-1.596c0.044-0.154-0.01-0.32-0.137-0.416C17.648,11.838,17.567,11.77,17.498,11.697 M16.671,13.334c-0.059-0.002-0.114-0.002-0.168-0.002c-1.749,0-3.173,1.422-3.173,3.172c0,0.053,0.002,0.109,0.004,0.166c-0.312,0.158-0.64,0.295-0.976,0.406c-0.039-0.045-0.077-0.086-0.115-0.123c-0.601-0.6-1.396-0.93-2.243-0.93s-1.643,0.33-2.243,0.93c-0.039,0.037-0.077,0.078-0.116,0.123c-0.336-0.111-0.664-0.248-0.976-0.406c0.002-0.057,0.004-0.113,0.004-0.166c0-1.75-1.423-3.172-3.172-3.172c-0.054,0-0.11,0-0.168,0.002c-0.158-0.312-0.293-0.639-0.405-0.975c0.044-0.039,0.085-0.078,0.124-0.115c1.236-1.236,1.236-3.25,0-4.486C3.009,7.719,2.969,7.68,2.924,7.642c0.112-0.336,0.247-0.664,0.405-0.976C3.387,6.668,3.443,6.67,3.497,6.67c1.75,0,3.172-1.423,3.172-3.172c0-0.054-0.002-0.11-0.004-0.168c0.312-0.158,0.64-0.293,0.976-0.405C7.68,2.969,7.719,3.01,7.757,3.048c0.6,0.6,1.396,0.93,2.243,0.93s1.643-0.33,2.243-0.93c0.038-0.039,0.076-0.079,0.115-0.123c0.336,0.112,0.663,0.247,0.976,0.405c-0.002,0.058-0.004,0.114-0.004,0.168c0,1.749,1.424,3.172,3.173,3.172c0.054,0,0.109-0.002,0.168-0.004c0.158,0.312,0.293,0.64,0.405,0.976c-0.045,0.038-0.086,0.077-0.124,0.116c-0.6,0.6-0.93,1.396-0.93,2.242c0,0.847,0.33,1.645,0.93,2.244c0.038,0.037,0.079,0.076,0.124,0.115C16.964,12.695,16.829,13.021,16.671,13.334 M10,5.417c-2.528,0-4.584,2.056-4.584,4.583c0,2.529,2.056,4.584,4.584,4.584s4.584-2.055,4.584-4.584C14.584,7.472,12.528,5.417,10,5.417 M10,13.812c-2.102,0-3.812-1.709-3.812-3.812c0-2.102,1.71-3.812,3.812-3.812c2.102,0,3.812,1.71,3.812,3.812C13.812,12.104,12.102,13.812,10,13.812"></path>
                            </svg>
                        </div>
                    </div>
                </div>
            </div>
            <div class="content">
            </div>
            <div class="input-area">
                <textarea name="text" id="textarea"></textarea>
                <div class="button-area">
                    <button id="stop-btn" class="talk_sub" style="display: none">停止生成</button>
                    <button id="del-btn" class="talk_sub">删除聊天记录</button>
                    <button id="chmod-btn" class="talk_sub">当前为普通对话</button>
                    <button id="send-btn" class="talk_sub">发 送</button>
                </div>
            </div>
        </div>

    </div>
<!--  当移动到消息框时显示的复制按钮 默认不显示，由js控制显示 -->
    <div class="menu" id="menu">
        <button class="menu-btn" id="copy-btn">复制</button>
        <button class="menu-btn" id="resend-btn">重新发送</button>
    </div>


</body>
<script>
    hljs.initHighlightingOnLoad();
    // 设置marked
    marked.marked.setOptions({
        renderer: new marked.Renderer(),
        highlight: function (code) {
            return hljs.highlightAuto(code).value;
        },
        pedantic: false,
        gfm: true,
        tables: true,
        breaks: false,
        sanitize: false,
        smartLists: true,
        smartypants: false,
        xhtml: false
    });
</script>
<script>
    function createHeaders() {
        return {
                "password": config.password,
                "api-key": config.apiKey,
                "user-id": encodeURIComponent(config.userId)
            };
    }
    // 当鼠标移动到 bubble-left时显示复制按钮
    $(document).on("mouseover", ".bubble-left", function () {
        let copyBtn = $("#menu");
        let copyBtnItem = $("#copy-btn");
        let offset = $(this).offset();
        // 右上角显示
        $("#resend-btn").hide();
        copyBtnItem.show();
        copyBtn.css("display", "block");
        copyBtn.css("top", offset.top);
        copyBtn.css("left", offset.left + $(this).width() - copyBtnItem.width() + 10);
        // 设置复制内容
        copyBtnItem.attr("data-clipboard-text", $(this).text());
    });
    // 移出bubble-left和菜单按钮时才恢复
    $(document).on("mouseleave", ".bubble-left", function () {
        // 若进入了菜单按钮 不关闭
        if (event.toElement.className === "menu-btn") {
            return;
        } else {
            $("#menu").css("display", "none");
        }
    });
    $(document).on("mouseleave", "#menu", function () {
        $("#menu").css("display", "none");
    });
    $(document).on("click", "#copy-btn", function () {
        let clipboard = new ClipboardJS('#copy-btn');
        clipboard.on('success', function (e) {
            console.log(e);
            // 将显示字符更改为复制成功，一秒后改回
            $("#copy-btn").text("复制成功");
            setTimeout(function () {
                $("#copy-btn").text("复制");
            }, 2000);
        });
        clipboard.on('error', function (e) {
            console.log(e);
        });
        // 光标回归
        $("#textarea").focus();
    });

    // 当鼠标移动到 bubble-right时显示重发按钮
    $(document).on("mouseover", ".bubble-right", function () {
        let menu = $("#menu");
        let resendBtn = $("#resend-btn");
        let offset = $(this).offset();
        // 右上角显示
        $("#copy-btn").hide();
        resendBtn.show();
        menu.css("display", "block");
        menu.css("top", offset.top);
        menu.css("left", offset.left + $(this).width() - resendBtn.width() + 10);
        // 设置复制内容
        resendBtn.attr("data-clipboard-text", $(this).text());
    });
    // 移出bubble-right和菜单按钮时才恢复
    $(document).on("mouseleave", ".bubble-right", function () {
        // 若进入了菜单按钮 不关闭
        if (event.toElement.className === "menu-btn") {
            return;
        } else {
            $("#menu").css("display", "none");
        }
    });
    $(document).on("mouseleave", "#menu", function () { // 移出菜单按钮
        $("#menu").css("display", "none");
    });
    $(document).on("click", "#resend-btn", function () {
        // 渲染到输入框
        let text = $(this).attr("data-clipboard-text");
        $("#textarea").val(text);
        // 模拟点击事件
        $("#send-btn").click();
        // 光标回归
        $("#textarea").focus();
    });
    $(document).on("mousewheel DOMMouseScroll", function(e) {
        // 当鼠标滚动时，隐藏菜单
        $("#menu").css("display", "none");
    });

    $("#userDictFileDownload").click(function () {
        // 弹出选择框，选项有两个，覆盖或合并
        let all = confirm("是否需要下载所有用户记录？\n下载所有用户记录需要管理员密码，点击取消将下载个人记录");
        let adminPassword = undefined;
        if (all) {
            adminPassword = prompt("请输入管理员密码");
            if (adminPassword === null) {
                return;
            }
            console.log("下载所有用户记录");
        } else {
            console.log("下载个人记录");
        }
        let headers = createHeaders();
        headers["admin-password"] = adminPassword;
        headers["cache-control"] = "no-cache"
        $.ajax({
            url: "/downloadUserDictFile",
            type: "Get",
            headers: headers,
            xhrFields: {        // 必要，不能设置为blob，不然将数据乱码，因为blob是高级封装，不是原始数据
                responseType: "arraybuffer"
            },
            success: function (data, status, xhr) {
                // 判断若不是文件
                if (xhr.getResponseHeader('Content-Type') !== "application/octet-stream") {
                    console.log("不是文件");
                    alert(data);
                    return;
                }

                let filename = "";
                let contentDisposition = xhr.getResponseHeader('Content-Disposition');
                if (contentDisposition && contentDisposition.indexOf('attachment') !== -1) {
                    let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    let matches = filenameRegex.exec(contentDisposition);
                    if (matches != null && matches[1]) {
                        filename = matches[1].replace(/['"]/g, '');
                    }
                }
                let binaryData = [];
                binaryData.push(data);
                let url = window.URL.createObjectURL(new Blob(binaryData, {type: "application/octet-stream"})); // 将二进制流转换为 URL 对象
                let a = document.createElement("a");
                a.style.display = "none";
                a.href = url;
                a.setAttribute("download", filename);
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                a = null;
            }
        });
    });
    $("#userDictFileUpload").change(function () {
        let file = this.files[0];
        let formData = new FormData();
        formData.append("file", file);
        let all = confirm("是否需要合并所有用户记录？\n合并所有用户记录需要管理员密码，点击取消将合并个人记录");
        let adminPassword = undefined;
        if (all) {
            adminPassword = prompt("请输入管理员密码");
            if (adminPassword === null) {
                return;
            }
            console.log("下载所有用户记录");
        } else {
            console.log("下载个人记录");
        }
        let headers = createHeaders();
        headers["admin-password"] = adminPassword;
        headers["cache-control"] = "no-cache"
        $.ajax({
            url: "/uploadUserDictFile",
            type: "POST",
            headers: headers,
            data: formData,
            processData: false,
            contentType: false,
            success: function (data) {
                alert(data);
                window.location.reload();
            }
        });
    });


</script>
<script>
    MathJax.Hub.Config({        // 公式配置
        showProcessingMessages: false, //关闭js加载过程信息
        messageStyle: "none", //不显示信息
        jax: ["input/TeX", "output/HTML-CSS"],
        tex2jax: {
          inlineMath: [["$", "$"], ["\\(", "\\)"]], //行内公式选择符
          displayMath: [["$$", "$$"], ["\\[", "\\]"]], //段内公式选择符
          skipTags: ["script", "noscript", "style", "textarea", "pre", "code", "a"] //避开某些标签
        },
        "HTML-CSS": {
          availableFonts: ["STIX", "TeX"], //可选字体
          showMathMenu: false //关闭右击菜单显示
        }
    });
</script>
<script>

    window.onload = function(){     //页面加载完成后，自动将光标定位至输入框
        document.getElementById('textarea').focus();
    }

    let newchat =  $("#newchat");

    function renderHeadInfo() {
        if (chats.length === 0) {   // 未登陆或授权
            $(".head-chat-name").text("未授权");
            $(".head-chat-info").text("当前浏览器未绑定用户或访问密码错误");
        } else {
            $(".head-chat-name").text(getSelectedChatInfo().name);
            // 判断 messages_of_chats 中是否存在selectedChatId
            if (messages_of_chats[selectedChatId] === undefined) {
                messages_of_chats[selectedChatId] = [];
            }
            $(".head-chat-info").text("共有" + messages_of_chats[selectedChatId].length + "条消息");
        }
    }
    function generateUUID() {
      let uuid = '', i, random
      for (i = 0; i < 32; i++) {
        random = Math.random() * 16 | 0
        if (i === 8 || i === 12 || i === 16 || i === 20) {
          uuid += '-'
        }
        uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)).toString(16)
      }
      return uuid
    }

    // getMode();
    function generateChatInfo(id) {
        return {
            "id": id,
            "name": "默认对话",
            "selected": true,
            "mode": "continuous",
            "memory_summarize": "你是一个AI助手",
            "last_summarize_index": 0
        };
    }
    let selectedChatId = generateUUID();
    let config = {"userId": null, "password": null, "apiKey": null, "chat_context_number": 5,
        "model_config": {"model": "gpt-3.5-turbo", "temperature": 0.9, "max_tokens": 2000}};
    let model_config = {"model": "gpt-3.5-turbo", "temperature": 0.9, "max_tokens": 2000};
    let chats = [generateChatInfo(selectedChatId)];
    let messages_of_chats = {[selectedChatId]: []};
    if (localStorage.getItem("chats") !== null) {
        chats = JSON.parse(localStorage.getItem("chats"));
    } else {
        localStorage.setItem("chats", JSON.stringify(chats));
    }
    if (localStorage.getItem("config") !== null) {
        config = JSON.parse(localStorage.getItem("config"));
    } else {
        localStorage.setItem("config", JSON.stringify(config));
    }
    if (localStorage.getItem("messages_of_chats") !== null) {
        messages_of_chats = JSON.parse(localStorage.getItem("messages_of_chats"));
    } else {
        localStorage.setItem("messages_of_chats", JSON.stringify(messages_of_chats));
    }
    selectedChatId = getSelectedId();


    function loadChats() {
        console.log("start load chats");
        let headers = createHeaders();
        $.ajax({
            url: "/loadChats",
            type: "Get",
            headers: headers,
            dataType: "json",
            success: function (data) {
                console.log(data);
                if(data.code === 200){
                    chats = data.data;
                    localStorage.setItem("chats", JSON.stringify(chats));
                }
                let html = "";
                for (let i = 0; i < chats.length; i++) {
                    console.log(chats[i].name)
                    console.log(chats[i].selected)
                    if(chats[i].selected === true){
                        selectedChatId = chats[i].id;
                        if(chats[i]["mode"]==="normal"){
                            $("#chmod-btn").text("当前为普通对话");
                        } else {
                            $("#chmod-btn").text("当前为连续对话");
                        }
                    }
                    html += '<div class="chat" id='+chats[i].id+' data-name='+chats[i].name+' data-selected='+chats[i].selected+' data-messages_total='+chats[i].messages_total+'>' + chats[i].name + '</div>';
                }
                if(chats.length === 0){     // 表示是未绑定用户状态
                    $("#del-btn").hide();
                    $("#chmod-btn").hide();
                    $(".chat-list").hide();
                } else {
                    $(".chat-list").append(html);
                    $(".chat-list").append(newchat);
                    // 将选中的selectedChat添加selected属性
                    $("#"+selectedChatId).addClass("selected");
                    if ($("#"+selectedChatId).data('name')!=='默认对话'){
                        $("#del-btn").html("删除对话");
                    } else {
                        $("#del-btn").html("删除聊天记录");
                    }
                }
                renderHeadInfo();
            }
        })
    }
    loadChats();

    $("#newchat").click(function () {
        console.log("请输入会话名称");
        let name = prompt("请输入会话名称");
        if (name === null) {
            return;
        }
        $.ajax({
            url: "/newChat",
            type: "Get",
            headers: createHeaders(),
            dataType: "json",
            data: {
                "name": name,
                "time": get_time_str(new Date()),
                "chat_id": generateUUID()
            },
            success: function (data) {
                console.log(data);
                if (data.code === 200 || data.code === 201) {
                    let html = '<div class="chat" id='+data.data.id+' data-name='+data.data.name+' data-selected='+data.data.selected+' data-messages_total='+data.data.messages_total+'>' + data.data.name + '</div>';
                    // newchat.remove();
                    $(".chat-list").append(html);
                    $(".chat-list").append(newchat);
                    $("#" + selectedChatId).removeClass("selected");
                    selectedChatId = data.data.id;
                    $("#"+selectedChatId).addClass("selected");
                    $("#del-btn").html("删除对话");
                    $('.content').empty();
                    let chat_info = generateChatInfo(selectedChatId);
                    chat_info["name"] = name;
                    chats.push(chat_info);
                    if(chat_info["mode"]==="normal"){
                        $("#chmod-btn").text("当前为普通对话");
                    } else {
                        $("#chmod-btn").text("当前为连续对话");
                    }
                    messages_of_chats[selectedChatId] = [];
                    localStorage.setItem("chats", JSON.stringify(chats));
                    loadHistory();
                    renderHeadInfo();
                }
            }
        })
    })


    $(".chat-list").on('click', '.chat', function () {
        let id = this.id;
        let click = this;
        console.log(id);
        $.ajax({
            url: "/selectChat",
            type: "Get",
            headers: createHeaders(),
            dataType: "json",
            data: {     // get 方法时 data放置于路径 ?id=
                "id": id
            },
            success: function (data) {
                console.log(data);
                if (data.code === 200 || data.code === 201) {
                    let chat_info = getSelectedChatInfo();
                    chat_info["selected"] = false;
                    $("#" + selectedChatId).removeClass("selected");
                    selectedChatId = id;
                    $(click).addClass("selected");
                    $('.content').empty();
                    if ($("#"+selectedChatId).data('name')!=='默认对话'){
                        $("#del-btn").html("删除对话");
                    } else {
                        $("#del-btn").html("删除聊天记录");
                    }
                    chat_info = getSelectedChatInfo();
                    chat_info["selected"] = true;
                    if(chat_info["mode"]==="normal"){
                        $("#chmod-btn").text("当前为普通对话");
                    } else {
                        $("#chmod-btn").text("当前为连续对话");
                    }
                    localStorage.setItem("chats", JSON.stringify(chats));
                    if (messages_of_chats[selectedChatId] === undefined) {
                        messages_of_chats[selectedChatId] = [];
                    }
                    loadHistory();
                    renderHeadInfo();
                }
            }
        })
    })

    function loadHistory() {
        console.log("start load history");
        if (messages_of_chats[selectedChatId] === undefined) {
            messages_of_chats[selectedChatId] = [];
        }
        $.ajax({
            url: "/loadHistory",
            type: "Get",
            headers: createHeaders(),
            dataType: "json",
            data: {
                "message_total": messages_of_chats[selectedChatId].length,
            },
            success: function (data) {
                console.log(data);
                let messages = [];
                if (data.code===200){   //200 时使用云端给的
                    messages = data.data;
                    messages_of_chats = {};
                    messages_of_chats[selectedChatId] = data.data;
                } else if (data.code===201){                // 201时使用浏览器本地的
                    if (messages_of_chats[selectedChatId].length===0){
                        messages_of_chats[selectedChatId] = data.data;
                    }
                    console.log('loadHistory'+201);
                    messages = messages_of_chats[selectedChatId];
                }
                localStorage.setItem("messages_of_chats", JSON.stringify(messages_of_chats));
                var html = "";
                for (var i = 0; i < messages.length; i++) {
                    if (messages[i].role === "user") {
                        html += '<div class="item item-right"><div class="bubble bubble-right">' + messages[i].content + '</div><div class="avatar"><img src="./static/people.jpg" /></div></div>';
                    } else if(messages[i].role === "assistant"){
                        html += '<div class="item item-left"><div class="avatar"><img src="./static/chatgpt.png" /></div><div class="bubble bubble-left markdown">' + marked.marked(messages[i].content) + '</div></div>';
                    } else if (messages[i].role === "web-system") {
                        html += '<div class="item item-center"><span>' + messages[i].content + '</span></div>';
                    }
                }
                $(".content").append(html);
                MathJax.Hub.Queue(["Typeset", MathJax.Hub, $(".content").get()]);   // 异步转换 放入队列中
                $(".content").scrollTop($(".content")[0].scrollHeight);

			    let preList = $(".markdown pre");
				preList.each(function(){
					let btn = $("<span class=\"code-copy-btn\" onclick='codeCopy(this)'>复制代码</span>");
			        btn.prependTo($(this));
				});
                renderHeadInfo();
            }
        });
    }
    loadHistory();

    function codeCopy(obj) {

        let btn = $(obj);
        console.log("复制代码");
        btn.text("");
        let code = btn.parent().text();
        btn.text("复制代码");

        // 使用 Clipboard.js 复制文本
        let clipboard = new ClipboardJS(obj, {
            text: function() {
                return code;
            }
        });

        // 显示复制结果
        clipboard.on('success', function(e) {
            console.log("复制成功");
            btn.text("复制成功");
            setTimeout(function(){
                btn.text("复制代码");
            }, 1000);
        });
        clipboard.on('error', function(e) {
            console.log("复制失败");
            btn.text("复制失败");
            setTimeout(function(){
                btn.text("复制代码");
            }, 1000);
        });
    }

    let returnMessageAjax = null;
    function get_time_str(time) {
        let year = time.getFullYear(); //得到年份
        let month = time.getMonth()+1;//得到月份
        let date = time.getDate();//得到日期
        let hour = time.getHours();//得到小时
        if (hour < 10) hour = "0" + hour;
        let minu = time.getMinutes();//得到分钟
        if (minu < 10) minu = "0" + minu;
        return year + "年" + month + "月" + date + "日 " + hour + ":" + minu
    }
    let last_time = 0

    function getSelectedChatInfo() {
        for(let i=0;i<chats.length;i++){
            if (chats[i].id===selectedChatId){
                return chats[i];
            }
        }
        return {};
    }
    function getSelectedId() {
        for (let i = 0; i < chats.length; i++) {
            if (chats[i].selected === true) {
                return chats[i].id;
            }
        }
    }

    $("#send-btn").click(function () {
        console.log("click")
        var text = $("#textarea").val();
        console.log("text");
        console.log(text);
        if (text == "") {
            alert("请输入内容");
            return;
        }
        let html = ''
        let send_time = new Date();
        let send_time_str = get_time_str(send_time);
        let display_time = false;
        if (send_time.getTime() - last_time > 1000 * 60 * 5) {
            // 以'%Y年%#m月%#d日 %H:%M'格式显示时间
            html += '<div class="item item-center"><span>' + get_time_str(send_time) + '</span></div>';
            last_time = send_time.getTime();
            display_time = true;

        }
        html += '<div class="item item-right"><div class="bubble bubble-right markdown">' + marked.marked(text) + '</div><div class="avatar"><img src="./static/people.jpg" /></div></div>';
        $(".content").append(html);
        $("#textarea").val("");
        $(".content").scrollTop($(".content")[0].scrollHeight);
        if(text.startsWith('new:')) send_time_str = get_time_str(send_time)
        let chat_item = $('<div class="item item-left"><div class="avatar"><img src="./static/chatgpt.png" /></div><div class="bubble bubble-left markdown">正在等待回复</div></div>')
        $(".content").append(chat_item);
        $(".content").scrollTop($(".content")[0].scrollHeight);
        let get_times = 0;
        messages_of_chats[selectedChatId].push({"role": "user", "content": text,"send_time": send_time_str, "display_time": display_time});
        renderHeadInfo();
        let start_index = 0;
        let get_total = 0;
        for (let i=messages_of_chats[selectedChatId].length-1;i>=1;i--){
            let role = messages_of_chats[selectedChatId][i].role;
            if (role === "user" || role === "assistant"){
                start_index = i;
                get_total += 1;
                if (get_total === config.chat_context_number){
                    // TODO 当用户按下切换按钮时，重新开始计数
                    break;      // 获得上下文起始位置 start_index
                }
            }
        }

        let message_contexts = [];
        let chat_info = getSelectedChatInfo();
        if ("mode" in chat_info && chat_info["mode"]!=="normal"){
            if("memory_summarize" in chat_info){
                message_contexts = [{"role": "system", "content": "历史聊天记录前情提要总结："+ chat_info.memory_summarize}];
            }
            for (let i=start_index;i<messages_of_chats[selectedChatId].length;i++){
                let role = messages_of_chats[selectedChatId][i].role;
                if (role === "user" || role === "assistant"){
                    message_contexts.push(messages_of_chats[selectedChatId][i]);
                }
            }
        } else {
            message_contexts = [messages_of_chats[selectedChatId][messages_of_chats[selectedChatId].length-1]];
        }

        let request_data = {
                "messages": message_contexts,
                "max_tokens": config.model_config.max_tokens || 2000,
                "model": config.model_config.model || "gpt-3.5-turbo",
                "temperature": config.model_config.temperature || 0.9,
                "stream": true,
                "continues_chat": true,
                "chat_id": selectedChatId,
                "save_message": true,
        };
        console.log("[Request]");
        console.log(request_data);
        let response_text =  "";
        let headers = createHeaders();
        headers["Content-Type"] = "application/json";
        let index = 0;
        let codeBacktickNum = 0;
        returnMessageAjax = $.ajax({
            url: "/returnMessage",
            headers: headers,
            data: JSON.stringify(request_data),
            type: "Post",
            dataType: "text",
            xhrFields: {
                onprogress: function (e) {
                    let response = e.currentTarget.response;
                    if (response.slice(index).includes("`")){
                        if (response.slice(index).includes("```")){
                            codeBacktickNum += 1;
                            index = response.length;
                        }
                        console.log("codeBacktickNum: "+codeBacktickNum);
                    } else {
                        index = response.length;
                    }
                    if (codeBacktickNum%2===1){
                        response += "\n```"
                    }
                    response_text = response;
                    // console.log(response);
                    if (response.includes("url_redirect")){
                        let response_json = JSON.parse(response.trim());
                        let url_redirect = response_json["url_redirect"];
                        // 判断user_id非空
                        if (response_json.hasOwnProperty("user_id") && response_json["user_id"] !== ""){
                            config.userId = response_json["user_id"];
                            localStorage.setItem("config", JSON.stringify(config));
                        }
                        window.location.href=url_redirect;

                    } else {
                        get_times += 1;
                        if (get_times === 2) {
                            $("#stop-btn").show();
                        }
                        let div =  document.createElement('div');
                        div.innerHTML = marked.marked(response);
                        MathJax.Hub.Typeset(div);
                        chat_item.find(".bubble").empty();
                        chat_item.find(".bubble").append(div);
                        $(".content").scrollTop($(".content")[0].scrollHeight);
                    }
                },
                onload: function (e) {
                    $("#stop-btn").hide();
                }
            },
            timeout: 1000 * 60 * 2,
            complete: function (XMLHttpRequest, status, e) {
                if (status === 'timeout') {
                    alert("请求超时");
                }
                $("#stop-btn").hide();
                let btn = $("<span class=\"code-copy-btn\" onclick='codeCopy(this)'>复制代码</span>");
                btn.prependTo(chat_item.find(".bubble").find("pre"));

                messages_of_chats[selectedChatId].push({"role": "assistant", "content": response_text, "send_time": get_time_str(new Date()), "display_time": false});
                localStorage.setItem("messages_of_chats", JSON.stringify(messages_of_chats));
                // getSummarize();
                renderHeadInfo();
            }
        });
    });

    function getSummarize(){
        // TODO 暂不使用
        let summarize = "";
        let chat_info = getSelectedChatInfo();
        if("mode" in chat_info && chat_info["mode"]==="normal"){  // 如果非连续对话模式，不进行总结
            return;
        }
        if("memory_summarize" in chat_info){
            summarize = chat_info.memory_summarize;
        } else {
            chat_info["memory_summarize"] = "";
        }
        let message_contexts = [{"role": "system", "content": "历史聊天记录前情提要总结："+ summarize }];
        let start_index = 0;
        if("last_summarize_index" in chat_info){
            start_index = chat_info["last_summarize_index"]+1;
        } else {
            chat_info["last_summarize_index"] = 0;
        }
        let end_index = messages_of_chats[selectedChatId].length-config.chat_context_number+1;
        if(end_index-start_index>5){  // 过长截断
            start_index = end_index-5;
        }
        if(start_index<1){
            start_index = 1;
        }
        for (let i = start_index; i <end_index; i++) {
            let role = messages_of_chats[selectedChatId][i].role;
            if (role === "user" || role === "assistant") {
                message_contexts.push(messages_of_chats[selectedChatId][i]);
            }
        }
        if (message_contexts.length===1){       // 如果没有需要总结的内容，直接返回
            return;
        }
        message_contexts.push({"role": "system", "content": "简要总结一下你和用户的对话，用作后续的上下文提示 prompt，控制在 50 字以内", "send_time": get_time_str(new Date()), "display_time": false})
        let request_data = {
                "messages": message_contexts,
                "max_tokens": 2000,
                "model": "gpt-3.5-turbo",
                "temperature": 0.9,
                "stream": true,
                "continues_chat": true,
                "chat_id": selectedChatId,
                "save_message": false,
        };
        console.log("[Memory Request]");
        console.log(request_data);
        let response_text =  "";
        let headers = createHeaders();
        headers["Content-Type"] = "application/json";
        $.ajax({
            url: "/returnMessage",
            headers: headers,
            data: JSON.stringify(request_data),
            type: "Post",
            dataType: "text",
            xhrFields: {
                onprogress: function (e) {
                    response_text = e.currentTarget.response;
                    console.log(response_text);
                },
            },
            complete: function (XMLHttpRequest, status, e) {
                if (status === 'timeout') {
                    alert("请求超时");
                }
                chat_info["memory_summarize"] = response_text;
                chat_info["last_summarize_index"] = end_index-1;
                console.log("[Memory Response]");
                console.log(response_text);
            }
        })
        // 改为fetch获取
        // let decoder = new TextDecoder("utf-8");
        // fetch("/returnMessage", {
        //   method: "POST",
        //   headers: {
        //     "Content-Type": "application/json",
        //     "user-id": config.userId,
        //     "password": config.password,
        //     "api-key": config.apiKey
        //   },
        //   body: JSON.stringify(request_data),
        // }).then((response) => {
        //   if (!response.ok) {
        //     throw new Error("Network response was not ok");
        //   }
        //   const reader = response.body.getReader();
        //   let responseText = '';
        //   return readStream();
//
        //   function readStream() {
        //     return reader.read().then(({ done, value }) => {
        //       if (done) {
        //         console.log(responseText);
        //         chat_info["memory_summarize"] = responseText;
        //         chat_info["last_summarize_index"] = end_index -1;
        //         return;
        //       }
        //       responseText += decoder.decode(value);
        //       console.log(responseText);
        //       return readStream();
        //     });
        //   }
//
        // }).catch((error) => {
        //   alert("Fetch API request failed with error:", error);
        // })


    }

    $("#stop-btn").click(function (){
        // 停止returnMessage请求
        if (returnMessageAjax != null) {

            returnMessageAjax.abort();
            returnMessageAjax = null;
        }
        $("#stop-btn").hide();
    });
    $("#textarea").keydown(function (e) {
        if (e.keyCode === 13 && !e.shiftKey) {
            e.preventDefault();
            $("#send-btn").click();
        }
    });
    $('#del-btn').click(function () {
        // 弹窗提醒是否确认删除
        if (confirm("确认删除所有聊天记录吗？非默认对话时将会直接删除该对话")) {
            $.get("/deleteHistory", function (data) {
                console.log(data);
            });
            let chat_info = getSelectedChatInfo();
            if(chat_info.name === "默认对话"){
                messages_of_chats[selectedChatId] = []
            } else {
                delete messages_of_chats[selectedChatId];
            }
            selectedChatId = chats[0].id;
            chats[0].selected = true;
            localStorage.setItem("messages_of_chats", JSON.stringify(messages_of_chats));
            localStorage.setItem("chats", JSON.stringify(chats));
            window.location.reload()
        }
    });
    $('#chmod-btn').click(function () {
        let chat_info = getSelectedChatInfo();
        if (!("mode" in chat_info)){
            chat_info["mode"] = "continuous";
        }
        let display_content = "";
        if(chat_info["mode"]==="normal"){
            chat_info["mode"] = "continuous";
            display_content = "切换为连续对话";
            $("#chmod-btn").text("当前为连续对话");
        } else {
            chat_info["mode"] = "normal";
            display_content = "切换为普通对话";
            $("#chmod-btn").text("当前为普通对话");
        }

        var html = '<div class="item item-center"><span>'+display_content+'</span></div>'
        $(".content").append(html);
        $(".content").scrollTop($(".content")[0].scrollHeight);
    });
</script>
</html>
